package com.zhengshang.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.zhengshang.api.domain.AppBillProduct;
import com.zhengshang.api.domain.AppBillRecord;
import com.zhengshang.api.domain.AppPayRecord;
import com.zhengshang.api.domain.OilcardAppPayRecord;
import com.zhengshang.api.service.IAppBillProductService;
import com.zhengshang.api.service.IAppBillRecordService;
import com.zhengshang.api.service.IAppPayRecordService;
import com.zhengshang.api.task.payorder.PayOrderCollection;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysDictData;
import com.zhengshang.common.core.domain.entity.SysRole;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.enums.UserStatus;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.uuid.IdUtils;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysDictTypeService;
import com.zhengshang.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//import fulu.sup.open.api.core.MethodConst;
//import fulu.sup.open.api.model.InputProductDto;
//import fulu.sup.open.api.sdk.DefaultOpenApiClient;

/**
 * @author HY
 * @version 1.0.0
 * @ClassName ViolationController.java
 * @Description TODO
 * @createTime 2021年06月07日 09:07
 */
@Api(tags = "话费充值接口")
@RestController
@RequestMapping("/bill")
public class BillProductController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppBillProductService appBillProductService;
    @Autowired
    private IAppBillRecordService appBillRecordService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private IAppPayRecordService appPayRecordService;
    @Autowired
    private ISysUserService userService;

//    @PostMapping("/getProductInfo")
//    public AjaxResult getProductInfo(
//            @RequestParam String productId,
//            HttpServletRequest request, HttpServletResponse response){
//        try {
//
//            DefaultOpenApiClient client =  new DefaultOpenApiClient(PhoneBillConstants.GETWAY_HTTPS, PhoneBillConstants.APP_KEY, PhoneBillConstants.APP_SECRET, MethodConst.OPEN_API_GOODS_GET);
//            InputProductDto dto = new InputProductDto();
//            dto.setProductId(productId);
//
//            client.setBizObject(dto);
//            return AjaxResult.success("查询成功", client.excute());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return AjaxResult.error("查询失败");
//    }

//    @PostMapping("/getOrderInfo")
//    public AjaxResult getOrderInfo(
//            @RequestParam String orderNum,
//            HttpServletRequest request, HttpServletResponse response){
//        try {
//
//            DefaultOpenApiClient client =  new DefaultOpenApiClient(PhoneBillConstants.GETWAY_HTTPS, PhoneBillConstants.APP_KEY, PhoneBillConstants.APP_SECRET, MethodConst.OPEN_API_ORDER_GET);
//            JSONObject bizContent = new JSONObject();
//            bizContent.put("customer_order_no", orderNum);
//            client.setBizContent(bizContent.toJSONString());
//            JSONObject jsonObject = JSONObject.parseObject(client.excute());
//            if (jsonObject.getIntValue("code") == 0) {
//                return AjaxResult.success(jsonObject.getJSONObject("result"));
//            }
//            return AjaxResult.error(jsonObject.getString("message"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return AjaxResult.error("查询失败");
//    }

    @PostMapping("/zhichong")
    public AjaxResult zhichong(
            @RequestParam String phone,
            @RequestParam Integer productId,
            HttpServletRequest request, HttpServletResponse response) {
        try {

            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_BILL);
            // DefaultOpenApiClient client =  new DefaultOpenApiClient(PhoneBillConstants.GETWAY_HTTP, PhoneBillConstants.APP_KEY, PhoneBillConstants.APP_SECRET, MethodConst.OPEN_API_DIRECT_ORDER_ADD);
            JSONObject bizContent = new JSONObject();
            bizContent.put("charge_account", phone);
            bizContent.put("buy_num", "1");
            bizContent.put("product_id", productId.toString());
            bizContent.put("customer_order_no", orderNum);
            logger.info("<zhichong>直充参数：{}", bizContent);
            //client.setBizContent(bizContent.toJSONString());
            // JSONObject jsonObject = JSONObject.parseObject(client.excute());
            JSONObject jsonObject = new JSONObject();
            logger.info("<zhichong>直充结果：{}", jsonObject);
//            System.out.println(jsonObject);
            if (jsonObject.getIntValue("code") == 0) {
                return AjaxResult.success(jsonObject.getJSONObject("result"));
            }
            return AjaxResult.error(jsonObject.getString("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "话费列表")
    @PreAuthorize("@ss.hasPermi('app:bill:all')")
    @PostMapping("/list")
    public AjaxResult list(HttpServletRequest request, @RequestParam(defaultValue = "1") Integer productType, @RequestParam(required = false, defaultValue = "0") Integer fast) {
        AjaxResult ajaxResult = new AjaxResult();
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        SysUser sysUser = userService.selectUserById(loginAppUser.getAppUser().getUserId());
        try {
            AppBillProduct billProduct = new AppBillProduct();
            billProduct.setProductType(productType);
            String activity = configService.selectConfigByKey("app.manmber.activity");
            if (ObjectUtils.isNotEmpty(activity) && activity.equals("1") && sysUser.getAppMemberType().equals("2")) {
                if (productType.equals(4) || productType.equals(5) || productType.equals(6)) {
                    billProduct.setRemark("110");
                }
            }
            ajaxResult = AjaxResult.success(appBillProductService.selectAppBillProductList(billProduct));
            if (productType.equals(2)) {
                List<JSONObject> list = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("text", "充值时间段为早上8点到晚上10点，此时间段以外勿冲。");
                list.add(jsonObject);
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("text", "全国三网话费快充，98折，正常1小小时内到账。");
                list.add(jsonObject2);
                String tips = configService.selectConfigByKey("app.phone.bill.fast.tips");
                ajaxResult.put("tips", tips);
            } else if (productType.equals(1)) {
                List<JSONObject> list = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("text", "充值72小时内到账，可能会分开到账，急用请采取快充。");
                list.add(jsonObject);
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("text", "携号转网,小号充值到账时间会慢,虚拟号段不支持充值业务。");
                list.add(jsonObject2);

                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.put("text", "充值前请核对充值号码，一经充值成功，无法退还。");
                list.add(jsonObject3);

                String tips = configService.selectConfigByKey("app.phone.bill.not.fast.tips");
                ajaxResult.put("tips", tips);

            } else {
                String tips = configService.selectConfigByKey("app.phone.bill.shjf.tips");
                ajaxResult.put("tips", tips);
            }
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "油卡充值配置列表")
    @PreAuthorize("@ss.hasPermi('app:bill:all')")
    @PostMapping("/oilcardProductList")
    public AjaxResult oilcardProductList(@RequestParam(defaultValue = "7") Integer productType) {
        AppBillProduct billProduct = new AppBillProduct();
        billProduct.setProductType(productType);
        List<AppBillProduct> list = appBillProductService.selectAppBillProductList(billProduct);
        AjaxResult ajaxResult = AjaxResult.success(list);
        String tips = configService.selectConfigByKey("app.phone.bill.oilcard.tips");
        ajaxResult.put("tips", tips);
        return AjaxResult.success(ajaxResult);
    }

    @ApiOperation(value = "优惠充值话费列表")
    @PostMapping("/couponList")
    public AjaxResult list2(
            HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        SysUser sysUser = userService.selectUserById(loginAppUser.getAppUser().getUserId());

        if ("1".equals(sysUser.getAppMemberType())) {
            return AjaxResult.error("请升级星级会员后使用");
        }
        Integer couponCount = ObjectUtils.isNotEmpty(sysUser.getCouponCount()) ? sysUser.getCouponCount() : 0;
        try {
            AppBillProduct billProduct = new AppBillProduct();
            billProduct.setProductType(10);
            if (couponCount > 0) {
                ajaxResult = AjaxResult.success(appBillProductService.selectAppBillProductList(billProduct));
                //优惠券金额
                String couponAmount = configService.selectConfigByKey("app.coupon.money");
                if (ObjectUtils.isNotEmpty(couponAmount)) {
                    ajaxResult.put("couponAmount", couponAmount);
                    ajaxResult.put("couponCount", couponCount);
                    ajaxResult.put("productTip", "当前充值金额100,实际到账110");
                }
            } else {
                ajaxResult = AjaxResult.success(new ArrayList<>());
            }
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "话费订单列表")
    @PreAuthorize("@ss.hasPermi('app:bill:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @PostMapping("/orderList")
    public AjaxResult orderList(
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false, defaultValue = "1") Integer productType,
            @RequestParam(required = false, defaultValue = "0") Integer fast,
            HttpServletRequest request, HttpServletResponse response) {

        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            AppBillRecord appBillRecord = new AppBillRecord();
            appBillRecord.setProductType(productType);
            //appBillRecord.setFast(fast);
            appBillRecord.getParams().put("pageNum", pageNum);
            appBillRecord.getParams().put("pageSize", pageSize);
            appBillRecord.setUserId(loginAppUser.getAppUser().getUserId());
            Map<String, SysDictData> dictDataMap = dictTypeService.selectDictDataByTypeToMap("app_bill_order_state");
            List<AppBillRecord> appBillRecordList = appBillRecordService.queryAppBillRecordList(appBillRecord);
            for (AppBillRecord billRecord : appBillRecordList) {
                SysDictData sysDictData = dictDataMap.get(billRecord.getOrderState());
                billRecord.setOrderStateStr(sysDictData == null ? "" : sysDictData.getDictLabel());
            }
            return AjaxResult.success(appBillRecordList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "油卡订单列表")
    @PreAuthorize("@ss.hasPermi('app:bill:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @GetMapping("/oilcardOrderList")
    public AjaxResult oilcardOrderList(
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) {

        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            AppPayRecord appPayRecord = new AppPayRecord();
            appPayRecord.setProductType(7);
            appPayRecord.setStatus("20");
            appPayRecord.setBuyType(AppConstant.ORDERNUM_PREFIX_OILCARD);
            appPayRecord.getParams().put("pageNum", pageNum);
            appPayRecord.getParams().put("pageSize", pageSize);
            appPayRecord.setUserId(loginAppUser.getAppUser().getUserId());
            Map<String, SysDictData> dictDataMap = dictTypeService.selectDictDataByTypeToMap("app_bill_order_state");
            List<OilcardAppPayRecord> appBillRecordList = appPayRecordService.queryOilcardOrderby(appPayRecord);
            for (OilcardAppPayRecord oilcardAppPayRecord : appBillRecordList) {
                SysDictData sysDictData = dictDataMap.get(oilcardAppPayRecord.getOrderState());
                oilcardAppPayRecord.setOrderState(sysDictData == null ? "" : sysDictData.getDictLabel());
            }
            return AjaxResult.success(appBillRecordList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }


    @ApiOperation(value = "号码归属地及运营商查询")
    @PreAuthorize("@ss.hasPermi('app:bill:all')")
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "money", value = "面值", required = false, dataType = "String", paramType = "query")
    })
    @PostMapping("/phoneInfo")
    public AjaxResult phoneInfo(@RequestParam String phone, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(phone)) {
            return AjaxResult.error("参数错误");
        }
        try {
            // DefaultOpenApiClient client =  new DefaultOpenApiClient(PhoneBillConstants.GETWAY_HTTPS, PhoneBillConstants.APP_KEY, PhoneBillConstants.APP_SECRET, MethodConst.OPEN_API_CHECK_PHONE);
            JSONObject bizContent = new JSONObject();
            bizContent.put("phone", phone);
            //client.setBizContent(bizContent.toJSONString());
            //JSONObject jsonObject = JSONObject.parseObject(client.excute());
            JSONObject jsonObject = new JSONObject();
            //if (jsonObject.getIntValue("code") == 0) {
            jsonObject.put("sp_typ", 1);
            jsonObject.put("province", "未知");
            jsonObject.put("sp", "");
            jsonObject.put("face_value", new JSONArray());
            return AjaxResult.success(jsonObject);
            // }
            //return AjaxResult.error(jsonObject.getString("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @PostMapping("/gateway")
    @ResponseBody
    public String gateway(@RequestBody JSONObject result, HttpServletRequest request, HttpServletResponse response) {
        try {

            logger.info("(<bill.gateway>充值回调成功，result={})", result);
            String orderStatus = result.getString("order_status");
            String orderNum = result.getString("customer_order_no");
            AppBillRecord appBillRecord = appBillRecordService.selectAppBillRecordByOrderNum(orderNum);
            if ("success".equals(orderStatus)) {
                appBillRecord.setOrderState("3");
            } else {
                appBillRecord.setOrderState("2");
            }
            String finishTime = result.getString("charge_finish_time");
            appBillRecord.setChargeFinishTime(StringUtils.isBlank(finishTime) ? DateUtils.getNowDate() : DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, finishTime));
            appBillRecord.setFuluOrderId(result.getString("order_id"));
            appBillRecord.setOperatorSerialNumber(result.getString("operator_serial_number"));
            appBillRecordService.updateAppBillRecord(appBillRecord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    @PostMapping("/refundGateway")
    @ResponseBody
    public String refundGateway(@RequestBody JSONObject result, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("(<bill.refundGateway>退款回调成功，result={})", result);
            String refundStatus = result.getString("refund_status");
            String orderNum = result.getString("customer_order_no");
            AppBillRecord appBillRecord = appBillRecordService.selectAppBillRecordByOrderNum(orderNum);
            if ("success".equals(refundStatus)) {
                appBillRecord.setOrderState("5");
                String refundTime = result.getString("refund_time");
                appBillRecord.setRefundTime(StringUtils.isBlank(refundTime) ? DateUtils.getNowDate() : DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, refundTime));
            } else {
                appBillRecord.setOrderState("6");
            }
            String finishTime = result.getString("refund_time");
            appBillRecord.setChargeFinishTime(StringUtils.isBlank(finishTime) ? DateUtils.getNowDate() : DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, finishTime));
            appBillRecord.setFuluOrderId(result.getString("order_id"));
            appBillRecord.setOperatorSerialNumber(result.getString("operator_serial_number"));
            appBillRecordService.updateAppBillRecord(appBillRecord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }


    /**
     * 查询订单支付信息
     *
     * @param request
     * @param payId
     * @return
     */
    @PostMapping("/getOrderPayInfo")
    public AjaxResult getOrderPayInfo(HttpServletRequest request, @RequestParam Long payId) {
        AppPayRecord appPayRecord = appPayRecordService.selectAppPayRecordById(payId);
        return AjaxResult.success(appPayRecord);
    }
}
